<template>
  <div class="stationSelect" v-loading="loading">
    <div class="title">选择你要查看的站点</div>
    <div class="checkMain">
      <el-checkbox-group v-model="checkedStation" :min="0">
        <el-checkbox v-for="site in stationList" :label="site" :key="site">
          {{ site }}
        </el-checkbox>
      </el-checkbox-group>
    </div>
    <el-button size="small" type="primary" @click="saveStation"
      >保 存</el-button
    >
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import posts from "@/plugins/request";
import storage from "@/plugins/localStorage";
export default {
  data() {
    return {
      loading: false,
      checkedStation: [],
      stationList: [],
    };
  },
  computed: {
    ...mapGetters({
      userInfo: "getUserInfo",
    }),
  },
  methods: {
    ...mapActions([
      "getStationListName",
      "fetchUserDetail",
      "getStationListName",
    ]),
    async saveStation() {
      this.loading = true;
      const checkedStation = this.checkedStation;
      const stationList = this.stationList;
      let payload = [];
      for (let i = 0; i < stationList.length; i++) {
        if (checkedStation.includes(stationList[i])) {
          payload.push({
            waterStation: stationList[i],
            isCheck: 0,
          });
        } else {
          payload.push({
            waterStation: stationList[i],
            isCheck: 1,
          });
        }
      }
      const result = await posts.postSiteSelection(payload);
      await this.getStationListName({ dataType: null });
      if (result.message === "success") {
        this.$notify({
          type: "success",
          title: "成功",
          message: result.info,
        });
      } else {
        this.$notify({
          type: "error",
          title: "警告",
          message: result.info,
        });
      }
      this.loading = false;
    },
  },
  async created() {
    await this.getStationListName({ dataType: null });
    this.loading = true;
    this.checkedStation = JSON.parse(storage.get("myStation"));
    const { stations } = await this.fetchUserDetail(this.userInfo.user.account);
    this.stationList = stations.map((v) => v.stationId);
    this.loading = false;
  },
};
</script>

<style scoped>
.stationSelect {
  background: #fff;
  min-height: 100%;
  padding: 0 20px 0 20px;
}
.stationSelect .title {
  position: relative;
  left: 15px;
  line-height: 70px;
  font-size: 16px;
}
.stationSelect .title::before {
  content: "";
  position: absolute;
  left: -15px;
  width: 4px;
  height: 20px;
  top: 25px;
  background-color: #2399ff;
}
.checkMain {
  width: 420px;
  margin-bottom: 25px;
}
.stationSelect .el-checkbox {
  width: 180px;
  margin-bottom: 12px;
}
</style>